import {Component, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, ParamMap, Router} from "@angular/router";
import {Http} from "@angular/http";
import {CamCalendarService} from "../../../shared/service/cam-calendar.service";
import {Vehicle} from "../../../shared/model/vehicle";
import {CalendarComponent} from "ap-angular2-fullcalendar";
import {Application} from "../../../shared/model/application";
import {MaintainRecord} from "../../../shared/model/maintainRecord";
declare var $: any;

@Component({
  selector: 'app-cam-calendar',
  templateUrl: './cam-calendar.component.html',
  styleUrls: ['./cam-calendar.component.css']
})
export class CamCalendarComponent implements OnInit {

  userId:string = this.routeInfo.snapshot.queryParams ["userId"];
  calendarOptions: Object;
  vehicle:Vehicle;
  applications:Application[];
  maintainRecord:MaintainRecord[];
  vehicleoid:string="";
  starttime:string;
  endtime:string;
  phase:string = "month";
  eventsInfo:any;

  @ViewChild(CalendarComponent) myCalendar: CalendarComponent;

  constructor(
    private router:Router,
    private http:Http,
    private routeInfo: ActivatedRoute,
    public camCalendarService:CamCalendarService
  ) { }

  ngOnInit() {
    if(this.routeInfo.snapshot.queryParams['vehicleoid']){
      this.vehicleoid = this.routeInfo.snapshot.queryParams['vehicleoid'];
      this.getCalendar();
    }else{
      this.getTimes();
      this.getCalendar();
    }
  }

  vehicleHandler(event: Vehicle){
    this.vehicle = event;
    this.vehicleoid = this.vehicle.oid;
    this.myCalendar.fullCalendar("refetchEvents");
  }

  firstVehicleHandler(event:Vehicle){
    this.vehicle = event;
    this.vehicleoid = this.vehicle.oid;

    if(this.routeInfo.snapshot.queryParams['vehicleoid']){
      this.vehicleoid = this.routeInfo.snapshot.queryParams['vehicleoid'];
    }
    // console.log("vehicleInfo"+this.vehicle.oid);
    //  this.myCalendar.fullCalendar("removeEvents");
    //  this.getCalendar();

    this.myCalendar.fullCalendar("refetchEvents");
  }

  getCalendar(){
    this.calendarOptions = {
      height : '800px',
      weekends:true,
      locale: 'zh-cn',
      views: {
        day: {
          titleFormat: 'YYYY年MM月DD日'
        },
        week: {
          titleFormat: 'YYYY年MM月'
        },
        month: { // name of view
          titleFormat: 'YYYY年MM月'
        },
      },

      header: {
        left: 'prev,next,today',
        center: 'title',
        right: 'agendaDay,agendaWeek,month'
      },
      buttonText:{
        today:'今天',
        month:'月',
        agendaWeek:'周',
        agendaDay:'日',
      },
      fixedWeekCount : false,
      defaultView:'month',
      defaultDate: new Date(),
      editable: false,
      liquid:true,
      eventLimit: true,
      events:(start,end,timezone, callback) =>{
        this.routeInfo.paramMap
          .switchMap((params: ParamMap) =>this.camCalendarService.getApplicationsByVehicle(start.format('YYYY-MM-DD').substr(0,10),end.format('YYYY-MM-DD').substr(0,10),this.vehicleoid))
          .subscribe(applications => {
            // console.log(start.format('YYYY-MM-DD HH:mm:ss').substr(0,16));
            // console.log(start.format('YYYY-MM-DD').substr(0,10));
              this.applications = applications;
              let events = [];
              for(let i=0;i<this.applications.length;i++){
                events.push({
                  start:this.applications[i].starttime,
                  end:this.applications[i].endtime,
                  title:this.applications[i].subject,
                  oid:this.applications[i].oid,
                  psn:this.applications[i].processsn,
                  color:this.resetEvents(this.applications[i].status)
                })
              }
              this.camCalendarService.getMaintainRecordsByVehicle(start.format('YYYY-MM-DD').substr(0,10),end.format('YYYY-MM-DD').substr(0,10),this.vehicleoid).then(maintainRecord=>{
                this.maintainRecord = maintainRecord;
                for(let i=0;i<this.maintainRecord.length;i++){
                  if(this.maintainRecord[i].status === 0){
                    this.maintainRecord[i].status = 6;
                  }
                  if(this.maintainRecord[i].status === 1){
                    this.maintainRecord[i].status = 7;
                  }
                  events.push({
                    start:this.maintainRecord[i].starttime,
                    end:this.maintainRecord[i].endtime,
                    title:this.maintainRecord[i].maintainItem,
                    oid:this.maintainRecord[i].oid,
                    psn:'',
                    color:this.resetEvents(this.maintainRecord[i].status)
                  })
                }
                this.eventsInfo = events;
                // console.log(this.eventsInfo);
                callback(events);
              });
            }
          )
      },
      dayClick : ( date, allDay, jsEvent ) => {
        let today = new Date();
        let startDate = date.format('YYYY-MM-DD HH:mm:ss');
        let type = jsEvent.type;
        let day = startDate.substr(0,10);
        let newdate = startDate.substr(8,2);
        let hour = startDate.substr(11,2);
        let minute = startDate.substr(14,2);

        let flag = true;
        if(parseInt(hour)< today.getHours()){
          flag = false;
        }else if(parseInt(hour) === today.getHours() && parseInt(minute)<today.getMinutes()){
          flag =false;
        }
        if(date<today && day !== today.getFullYear()+"-"+(Array(2).join("0")+(today.getMonth() + parseInt("1")))+"-"+(Array(2).join("0")+today.getDate()).slice(-2)){
          alert("申请日期需大于当前日期，今天的车辆申请请到用车查询页面操作！");
          return false;
        }else  if( (type !== "month") &&(day === today.getFullYear()+"-"+(Array(2).join("0")+(today.getMonth() + parseInt("1")))+"-"+(Array(2).join("0")+today.getDate()).slice(-2)) &&(flag === false)){
          alert("车辆开始时间不能小于当前时间！");
        }else{

          let endDate = "";
          if(type === "month"){
            if((day === today.getFullYear()+"-"+(today.getMonth() + parseInt("1"))+"-"+(Array(2).join("0")+today.getDate()).slice(-2))){
              if(9 > today.getHours()){
                startDate = day+" 09:00";
              }else if(today.getMinutes()<30){
                startDate = day+" "+(Array(2).join("0")+today.getHours()).slice(-2)+":30";
              }else{
                startDate = day+" "+(Array(2).join("0")+(today.getHours()+ parseInt("1"))).slice(-2)+":00";
              }
            }else{

              startDate = day+" 09:00";
            }
            endDate = day+" 18:00";
          }else{
            if(minute ==="00"){
              startDate = day+" "+hour+":00";
              endDate = day+" "+hour+":30";
            }else {
              startDate = day+" "+hour+":30";
              if(hour !== "23") {
                hour = parseInt(hour) + parseInt("1");
              }
              if(parseInt(hour)<10){
                hour = "0"+hour;
              }

              if(parseInt(hour) ===23){
                endDate = day+" "+hour+":59";
              }else{
                endDate = day+" "+hour+":00";
              }

            }
          }

          this.router.navigate(["camApplyByUser",{startdate:startDate.substr(0,10),enddate:endDate.substr(0,10)}],{ queryParams: { userId: this.userId,flag:"calendar"} });

          return false;
        }
      },
      eventClick:  (event) =>{
        if(event.psn) {
          // console.log(event);
          this.router.navigate(["/camDetail"],{ queryParams: { userId:this.userId,comeBack:"camCalendar",psn:event.psn}});
          return false;
        }else{
          this.router.navigate(["/camMaintainRecordDetail"],{ queryParams: { userId:this.userId,comeBack:"camCalendar",oid:event.oid}});
          return false;
        }
      }
    };
  }

  getTimes(){
    let date = new Date();
    let defaultyear = date.getFullYear();
    let defaultmonth = date.getMonth();
    let month = defaultmonth+1;
    let days = new Date(defaultyear,defaultmonth+1,0);
    /*this.starttime = defaultyear+"-"+month+"-01 00:00";
    this.endtime = defaultyear+"-"+month+"-"+days.getDate()+" 23:59";*/
    this.starttime ="2017-09-01 00:00";
    this.endtime ="2017-10-31 23:59";
    // console.log(this.starttime+"   "+this.endtime);
  }

  //不同颜色状态设置
  resetEvents(status:number):string{
    if(status ===0){
      // return "#F4B917";
      return "#428BCB";
    }else if(status ===1){
      return "#428BCB";
    }else if(status === 6){
      return "#D9524E";
    }else if(status === 7){
      return "#F1AD4E";
    }
  }

  btn_apply(){
    this.router.navigate(["camApplyByUser"],{queryParams:{userId:this.userId,flag:"calendar"}});
  }

}
